package com.example.springmvc_demo2.controller;

import com.example.springmvc_demo2.entity.Student;
import com.example.springmvc_demo2.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public String listStudents(Model model) {
        List<Student> students = studentService.getAllStudents();
        model.addAttribute("students", students);
        return "student_list";
    }

    @GetMapping("/add")
    public String addStudentForm(Model model) {
        model.addAttribute("student", new Student());
        model.addAttribute("action", "add");
        return "student_form";
    }

    @PostMapping("/add")
    public String addStudent(@ModelAttribute Student student, RedirectAttributes redirectAttributes) {
        if (studentService.addStudent(student)) {
            redirectAttributes.addFlashAttribute("successMessage", "学生添加成功！");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "学生添加失败，学号可能已存在。");
        }
        return "redirect:/students";
    }

    @GetMapping("/edit/{id}")
    public String editStudentForm(@PathVariable Long id, Model model) {
        Student student = studentService.getStudentById(id);
        if (student == null) {
            // Handle not found case, e.g., redirect to list with error
            return "redirect:/students";
        }
        model.addAttribute("student", student);
        model.addAttribute("action", "edit");
        return "student_form";
    }

    @PostMapping("/edit")
    public String updateStudent(@ModelAttribute Student student, RedirectAttributes redirectAttributes) {
        if (studentService.updateStudent(student)) {
            redirectAttributes.addFlashAttribute("successMessage", "学生信息更新成功！");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "学生信息更新失败，学号可能已存在或学生不存在。");
        }
        return "redirect:/students";
    }

    @PostMapping("/delete/{id}")
    public String deleteStudent(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        if (studentService.deleteStudent(id)) {
            redirectAttributes.addFlashAttribute("successMessage", "学生删除成功！");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "学生删除失败。");
        }
        return "redirect:/students";
    }
} 